package com.java.base.exercise.current;

import org.omg.PortableServer.Servant;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @Author RenPu
 * @Date 2022/1/11 15:43
 * @Version 1.0
 * @Description: 主动对象模式
 **/
public class ActiveObject {




static class CustomInvocationHandler implements InvocationHandler{

    private Object target;

    private ExecutorService service;

   public CustomInvocationHandler(Object target,ExecutorService service){
       this.target=target;
       this.service=service;
   }

    @Override
    public Object invoke(Object o, Method method, Object[] args) throws Throwable {
//        Object result = method.invoke(args);

        Future<Object> submit = service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {

                //执行真正的业务逻辑
                return null;
            }
        });
        return submit;


    }


    /**
     * 用静态代理的方式来实现Proxy，相对于动态代理，其执行效率会更高一点，但缺点是需要提前编写好静态代理类，
     * 而且这个代理类难以扩展，当后面需求有变化时，需要修改甚至新建代理类，从而使得Proxy难以被复用。
     * @param interfaces
     * @param service
     * @param servant
     * @param <T>
     * @return
     */

    public static <T> T newInstance(Class<T> interfaces, ExecutorService service, Servant servant){

        CustomInvocationHandler customInvocationHandler = new CustomInvocationHandler(servant,service);

        T proxyInstance=(T)Proxy.newProxyInstance(interfaces.getClassLoader(),new Class[]{interfaces},customInvocationHandler);

        return proxyInstance;

    }





}


}
